<template>
  <div class="app-container">
    <el-tabs
      v-model="tab"
      @tab-click="tabsChange"
      v-if="userInfo.userType == 1"
    >
      <el-tab-pane label="全部订单" name="0"></el-tab-pane>
      <el-tab-pane
        :label="`待支付(${tabStatus.toBePaid || 0})`"
        name="1,4"
      ></el-tab-pane>
      <el-tab-pane
        :label="`待发货(${tabStatus.toBeShipped || 0})`"
        name="16"
      ></el-tab-pane>
      <el-tab-pane
        :label="`待确认(${tabStatus.toBeConfirmed || 0})`"
        name="13"
      ></el-tab-pane>
      <el-tab-pane
        :label="`待完成(${tabStatus.toBeCompleted || 0})`"
        name="10,11,14,17,19,21"
      ></el-tab-pane>
      <el-tab-pane
        :label="`待退款(${tabStatus.pendingRefund || 0})`"
        name="6,7,8"
      ></el-tab-pane>
      <el-tab-pane label="成功的订单" name="12,15,18,20"></el-tab-pane>
      <el-tab-pane label="关闭的订单" name="2,8,9"></el-tab-pane>
    </el-tabs>

    <!-- 筛选区域 -->
    <el-form
      ref="listFilterRef"
      :model="list.filter"
      inline
      class="list-filter"
    >
      <el-form-item prop="likeOrderId">
        <el-input
          v-model="list.filter.likeOrderId"
          placeholder="搜索订单号"
          clearable
        />
      </el-form-item>
      <el-form-item prop="productName">
        <el-input
          v-model="list.filter.productName"
          placeholder="搜索商品名称"
          clearable
        />
      </el-form-item>
      <el-form-item prop="purchaserName">
        <el-input
          v-model="list.filter.purchaserName"
          placeholder="搜索联系人姓名"
          clearable
        />
      </el-form-item>
      <el-form-item prop="purchaserPhone">
        <el-input
          v-model="list.filter.purchaserPhone"
          placeholder="搜索联系人手机号"
          clearable
        />
      </el-form-item>
      <el-form-item prop="payNo">
        <el-input
          v-model="list.filter.payNo"
          placeholder="搜索支付单号"
          clearable
        />
      </el-form-item>
      <el-form-item prop="belongMerchantId">
        <merchantSelect
          v-model="list.filter.belongMerchantId"
          noPermission
          placeholder="所属商户"
        />
      </el-form-item>
      <el-form-item prop="saleMerchantId">
        <merchantSelect
          v-model="list.filter.saleMerchantId"
          noPermission
          placeholder="销售商户"
        />
      </el-form-item>
      <el-form-item prop="belongSubMerchantId">
        <KiSelect
          v-model="list.filter.belongSubMerchantId"
          :options="submerchantOpt"
          :props="{ value: 'subMchId', label: 'name' }"
          placeholder="所属店铺"
        />
      </el-form-item>
      <el-form-item prop="saleSubMerchantId">
        <SubMchSelect
          v-model="list.filter.saleSubMerchantId"
          noPermission
          placeholder="销售店铺"
        />
      </el-form-item>
      <el-form-item prop="businessTypeId">
        <KiSelect
          v-model="list.filter.businessTypeId"
          :options="productTypeOpt"
          :props="{ value: 'id', label: 'name' }"
          placeholder="商品类型"
        />
      </el-form-item>
      <el-form-item v-if="!tab || tab == 0" prop="statusArray">
        <KiSelect
          v-model="list.filter.statusArray"
          :options="orderStatus"
          placeholder="订单状态"
          multiple
          collapse-tags
        />
      </el-form-item>
      <el-form-item prop="triggerOperationArray" v-if="!tab || tab == 0">
        <KiSelect
          v-model="list.filter.triggerOperationArray"
          :options="orderStatusType"
          placeholder="订单状态类型"
          multiple
          collapse-tags
        />
      </el-form-item>
      <el-form-item prop="payStatusArray">
        <KiSelect
          v-model="list.filter.payStatusArray"
          :options="payStatus"
          placeholder="支付状态"
          multiple
          collapse-tags
        />
      </el-form-item>
      <el-form-item prop="thirdStatusArray">
        <KiSelect
          v-model="list.filter.thirdStatusArray"
          :options="thirdStatus"
          placeholder="票务状态"
          multiple
          collapse-tags
        />
      </el-form-item>
      <el-form-item prop="endOrderTime">
        <TimeRangePicker
          :start.sync="list.filter.beginOrderTime"
          :end.sync="list.filter.endOrderTime"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="date-time"
          placeholder="下单开始时间/下单结束时间"
        />
      </el-form-item>
      <el-form-item prop="useEndDate">
        <TimeRangePicker
          :start.sync="list.filter.useStartDate"
          :end.sync="list.filter.useEndDate"
          type="date-time"
          placeholder="预定开始时间/预定结束时间"
        />
      </el-form-item>
      <el-form-item prop="endCompleteTime">
        <TimeRangePicker
          :start.sync="list.filter.startCompleteTime"
          :end.sync="list.filter.endCompleteTime"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="date-time"
          placeholder="订单完成开始时间/订单完成结束时间"
        />
      </el-form-item>
      <el-form-item prop="payMethod">
        <KiSelect
          v-model="list.filter.payMethod"
          :options="payMethodList"
          placeholder="支付方式"
        />
      </el-form-item>
      <el-form-item prop="discountOrder">
        <KiSelect
          v-model="list.filter.discountOrder"
          :options="[
            { dataName: '是', dataValue: '1' },
            { dataName: '否', dataValue: '0' }
          ]"
          placeholder="优惠订单"
        />
      </el-form-item>
      <el-form-item prop="productSource">
        <KiSelect
          v-model="list.filter.productSource"
          :options="[
            { dataName: '是', dataValue: '1' },
            { dataName: '否', dataValue: '0' }
          ]"
          placeholder="是否为云仓商品"
        />
      </el-form-item>

      <el-form-item>
        <el-button @click="reset">
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 分页,表格头部按钮 -->
    <div class="table-operation">
      <span>
        <ExportExcel
          url="/sot-admin-api/order/query/downloadOrderList"
          name="导出列表"
          :param="list.filter"
        />
      </span>
      <!-- 分页 -->
      <el-pagination
        v-bind="elPaginationProps"
        :total="list.total"
        :currentPage.sync="list.filter.pageNo"
        :pageSize.sync="list.filter.pageSize"
      />
    </div>

    <!-- 表格 -->
    <el-table v-loading="list.loading" :data="list.data" v-bind="tableProp">
      <el-table-column label="商品名称" prop="productName" width="140" />
      <el-table-column label="订单号" prop="orderId" width="140" />
      <el-table-column label="支付单号" prop="payNo" width="140" />
      <el-table-column label="支付方式" prop="payMethod" width="140">
        <template v-slot="{ row }">
          {{ row.payMethod.toString() | $value2label(payMethodList) }}
        </template>
      </el-table-column>
      <el-table-column label="商品类型" prop="businessTypeName" width="80" />
      <el-table-column label="商品单价(元)" width="110">
        <template v-slot="{ row }">
          {{ (row.currentPrice / row.quantity) | $cent2yuan }}
        </template>
      </el-table-column>
      <el-table-column label="商品数量" prop="quantity" width="80" />
      <el-table-column label="优惠金额(元)" prop="discountPrice" width="110">
        <template v-slot="{ row }">
          <span>{{ row.discountPrice | $cent2yuan }}</span>
        </template>
      </el-table-column>

      <el-table-column label="平台补差(元)" width="110">
        <template v-slot="{ row }">
          <span>{{ row.makeUpDifferenceAmount | $cent2yuan }}</span>
          <div>
            {{
              row.makeUpDifferenceStatus
                | $value2label(dict['make_up_difference_status'])
            }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="订单总价(元)" width="110">
        <template v-slot="{ row }">
          <span>{{ row.currentPrice | $cent2yuan }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实付金额(元)" width="110">
        <template v-slot="{ row }">
          <span>{{ row.paidPrice | $cent2yuan }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实收金额(元)" width="110">
        <template v-slot="{ row }">
          <span>{{ row.netReceiptsPrice | $cent2yuan }}</span>
        </template>
      </el-table-column>

      <!-- v-if="isPintai" -->
      <el-table-column
        label="所属店铺"
        prop="belongSubMerchantName"
        width="140"
      />
      <el-table-column label="所属商户" prop="belongMerchantName" width="140" />
      <el-table-column
        label="销售店铺"
        prop="saleSubMerchantName"
        width="140"
      />
      <el-table-column label="销售商户" prop="saleMerchantName" width="140" />
      <el-table-column label="状态" prop="orderStatusName" />
      <el-table-column label="支付状态" prop="payStatusName" width="80" />
      <el-table-column label="票务状态" prop="thirdStatusName" width="80" />
      <el-table-column label="预订人/收货人信息" width="140" align="left">
        <template v-slot="{ row }">
          <!-- 预订人 -->
          <span>
            <i class="el-icon-user-solid"></i>
            {{ row.purchaserName }}
          </span>
          <!-- 电话 -->
          <div v-if="row.purchaserPhone">
            <i class="el-icon-phone"></i>
            {{ row.purchaserPhone }}
          </div>
          <!-- 省市,收货地址 -->
          <div
            v-if="
              row.receiptInfo &&
                (row.receiptInfo.areaName || row.receiptInfo.address)
            "
          >
            <i class="el-icon-s-home"></i>
            {{ row.receiptInfo.areaName }}，{{ row.receiptInfo.address }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="下单时间" prop="orderTime" width="100" />
      <el-table-column label="预定时间" prop="useStartTime" width="100">
        <template v-slot="{ row }">
          <span v-if="row.businessTypeId == 4">
            {{ row.useStartTime.split(' ')[0] }}
          </span>
          <span v-else>{{ row.useStartTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="完成时间" prop="completeTime" width="100" />
      <el-table-column label="操作" width="200" fixed="right">
        <template v-slot="{ row }">
          <auth-button name="查看" @click="$refs.viewPage.open(row.orderId)" />
          <auth-button
            name="预定确认"
            @click="$refs.acceptOrderPage.open(row.orderId)"
            v-if="row.status == 13"
          />
          <auth-button
            name="退款审批"
            @click="$refs.refundApprovalPage.open(row.orderId)"
            v-if="row.status == 6"
          />
          <!-- <el-button @click="goSure(row)">退款审批</el-button> -->
          <!-- 退款/拒绝预定/拒绝发货（old：有问题就退回逻辑） v-if="!(row.payStatus == 9  || row.status == 6 || row.payStatus == 7)"-->
          <!-- 退款/拒绝预定/拒绝发货（new：有问题就退回逻辑） -->
          <auth-button
            :name="getRefundName(row)"
            @click="refundPageOpen(row)"
            v-if="row.refundableForPc"
          />

          <auth-button
            name="入住办理"
            @click="$refs.checkInPage.open(row.orderId)"
            v-if="row.status == 14"
          />
          <auth-button
            name="检票"
            @click="$refs.ticketCheckPage.open(row.orderId)"
            v-if="
              (row.status == 11 || row.status == 19 || row.status == 21) &&
                (row.businessTypeId == 3 || row.businessTypeId == 1)
            "
          />
          <auth-button
            name="发货"
            @click="$refs.deliverPage.open(row.orderId)"
            v-if="row.status == 16"
          />
          <auth-button
            name="物流信息"
            @click="$refs.logistics.open(row)"
            v-if="row.businessTypeId == 5 && row.status > 6 && row.status != 16"
          />
          <ExportExcel
            url="/sot-admin-api/order/query/downloadOrderDetail"
            name="导出订单详情"
            :param="{
              orderId: row.orderId
            }"
            type="text"
            icon="-"
          />
          <auth-button
            name="退款记录"
            @click="$refs.refundLog.open(row)"
            v-if="row.refundApply"
          />
          <auth-button
            name="手动分账"
            @click="separateAccount(row)"
            v-if="isPintai && row.distributeStatus == 2"
          />

          <auth-button
            name="手动补差"
            v-if="row.makeUpDifferenceStatus == 2"
            @click="handleCompensation(0, row)"
          />
          <auth-button
            name="手动退款补差"
            v-if="row.makeUpDifferenceStatus == 7"
            @click="handleCompensation(1, row)"
          />
        </template>
      </el-table-column>
    </el-table>

    <!-- 弹窗 -->
    <viewPage ref="viewPage"></viewPage>
    <logistics ref="logistics"></logistics>
    <refundApprovalPage
      ref="refundApprovalPage"
      @save="getList"
    ></refundApprovalPage>
    <acceptOrderPage ref="acceptOrderPage" @save="getList"></acceptOrderPage>
    <refundPage ref="refundPage" @save="getList"></refundPage>
    <rejectPage ref="rejectPage" @save="getList"></rejectPage>
    <checkInPage ref="checkInPage" @save="getList"></checkInPage>
    <delivery ref="deliverPage" @save="getList"></delivery>
    <ticketCheckPage ref="ticketCheckPage" @save="getList"></ticketCheckPage>
    <refundLog ref="refundLog"></refundLog>
    <rule ref="rule" />
  </div>
</template>
<script>
import API from './components/api'
import { mapGetters } from 'vuex'
import { parseTime } from '@/utils'
import viewPage from './components/viewPage'
import logistics from './components/logistics'
import refundApprovalPage from './components/refundApprovalPage'
import acceptOrderPage from './components/acceptOrderPage'
import refundPage from './components/refundPage'
import rejectPage from './components/rejectPage'
import checkInPage from './components/checkInPage'
import delivery from './components/delivery'
import ticketCheckPage from './components/ticketCheckPage'
import refundLog from './components/refundLog'
import rule from './components/rule'
import merchantSelect from '@/components/merchantSelect'
import SubMchSelect from '@/components/SubMchSelect'
import pageMixin from '@/utils/pageMixin'
import useAdmateAdapter from '@/utils/useAdmateAdapter'
import orderDict from './components/orderDict.js'
let _this = null

export default {
  components: {
    viewPage,
    logistics,
    refundApprovalPage,
    acceptOrderPage,
    refundPage,
    checkInPage,
    delivery,
    ticketCheckPage,
    refundLog,
    rejectPage,
    rule,
    merchantSelect,
    SubMchSelect
  },
  mixins: [pageMixin],
  setup: () =>
    useAdmateAdapter(
      {
        urlPrefix: 'sot-admin-api/order/query',
        axiosConfig: {
          getList: {
            url: 'queryOrderList'
          }
        },
      },
      {
        afterGetList () {
          let filter = _this.$lo.cloneDeep(_this.list.filter)
          delete filter.pageNo
          delete filter.pageSize
          delete filter.status
          delete filter.statusArray
          // tab标签状态数
          API.getStatusCount(filter).then(({ data }) => {
            if (data) _this.tabStatus = data
          })
          //_this.computeTableHeight() // 计算页面高度
        }, // 请求列表之后
        initialListFilter () {
          return {
            beginOrderTime: parseTime(
              new Date(new Date() - 1000 * 60 * 60 * 24 * 60)
            ),
            endOrderTime: parseTime(new Date())
          }
        }
      }
    ),
  data () {
    return {
      tableData: [],
      tab: '',
      tabStatus: {},
      submerchantOpt: [], //所属店铺
      ...orderDict, //支付方式
      updateListWait: false //更新列表队列等待, 防止多次更新
    }
  },
  computed: {
    ...mapGetters(['userInfo']),
    isPintai () {
      //是否平台
      return this.userInfo.userType == 0
    }
  },
  created () {
    _this = this
    // 下拉选项
    if (!this.isPintai) {
      // 所属店铺
      API.getSubmerchant({
        merchantId: this.userInfo.merchantId
      }).then(({ data }) => {
        this.submerchantOpt = data
      })
    }
  },
  methods: {
    goSure (row) {
      this.$refs.rule.open(row)
    },
    // 退款、退款审批
    sureRefund (row) {
      // const isInitiative = [8, 11, 21, 13, 14, 16, 17, 19]
      // if(row.status==6){
      //     // 退款审批
      //     this.$refs.refundApprovalPage.open(row.orderId)
      // }else{
      //     // 退款
      //     if (row.status == 12 && row.orderProductAttribute.checkedRefund == 1) {
      //     this.refundPageOpen(row)
      //     } else if (isInitiative.includes(row.status)) {
      //     this.refundPageOpen(row)
      //     }
      // }
      // 退款审批不需要二次确认弹框
      if (row.refundableForPc) {
        this.$refs.refundPage.open(row)
      }
    },
    /**
     * 构建接口订单状态参数
     * @param status {String} 订单状态
     * @param statusArray {Array} 订单状态集合
     */
    tabsChange (tab) {
      const tabStr = tab.name == 0 ? '' : tab.name
      if (tabStr.indexOf(',') > 0) {
        delete this.list.filter.status
        this.list.filter.statusArray = tabStr.split(',')
      } else {
        delete this.list.filter.statusArray
        this.list.filter.status = tabStr
      }
      this.getList()
    },
    getRefundName (row) {
      // const isInitiative = [8, 11, 21, 13, 14, 16, 17, 19]
      if (row.businessTypeId == 4 && row.status == 13) {
        // 酒店
        return '拒绝预定'
      } else if (row.businessTypeId == 5 && row.status == 16) {
        // 实物
        return '拒绝发货'
      }
      // else if (row.status == 12 && row.orderProductAttribute.checkedRefund == 1) {
      //     return '退款'
      // } else if (isInitiative.includes(row.status)) {
      //     return '退款'
      // }
      // 上的判断是以前逻辑，现在refundableForPc控制退款是否显示
      else if (row.refundableForPc) {
        return '退款'
      }
      return ''
    },
    refundPageOpen (row) {
      // 已检票需要提示对应弹框
      //12表示已检票
      if (row.status == 12) {
        // this.$confirm('当前门票为已检票状态，当前退款会向支付系统发起退款申请，请保证企业账户中有足够余额，不然会退款失败。当前退款不会改变订单状态，仍然为已检票。是否确定要退款？')
        //     .then(() => {
        //         this.$refs.refundPage.open(row)
        //     })
        this.goSure(row)
      } else if (
        (row.businessTypeId == 4 && row.status == 13) ||
        (row.businessTypeId == 5 && row.status == 16)
      ) {
        this.$refs.rejectPage.open(row)
      } else {
        // 15-已入住
        // 18-已收货
        // 20-已使用
        // 12-已检票
        if (
          (row.status == 15 || row.status == 20 || row.status == 18) &&
          row.refundableForPc
        ) {
          this.goSure(row)
        } else {
          this.$refs.refundPage.open(row)
        }
        // this.$refs.refundPage.open(row)
      }
    },
    separateAccount (row) {
      //进行手动分账
      this.$msgbox({
        title: '手动分账',
        message: `<p>${row.orderId} ${row.productName} × ${row.quantity}</p><p>确定对该订单进行手动分账？</p>`,
        dangerouslyUseHTMLString: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        showCancelButton: true,
        type: 'warning'
      })
        .then(() => {
          this.loading = true
          API.separateAccount({
            orderId: row.orderId
          })
            .then(() => {
              this.$swal({
                type: 'success',
                message: '操作成功!'
              })
              this.getList()
            })
            .finally(() => {
              this.loading = false
            })
        })
        .catch(() => {})
    },
    handleCompensation (tag, row) {
      this.compensationcCount++
      let title = '',
        cont = '',
        info = '',
        url = '',
        type = ''
      let amount =
        row.makeUpDifferenceAmount > 0
          ? (row.makeUpDifferenceAmount / 100).toFixed(2)
          : 0
      if (tag) {
        title = `手动退款补差【订单号${row.orderId}】`
        cont = `是否确认手动退款补差${amount}元？`
        info = `手动退款补差请确保商户的微信账户号内的钱足够`
        type = '手动退款补差'
        url = `/sot-admin-api/order/makeUpDifference/returnSubsidy`
      } else {
        title = `手动补差【订单号${row.orderId}】`
        cont = `是否确认手动补差${amount}元？`
        info = `手动补差请确保平台微信账户号内的钱足够`
        type = '手动补差'
        url = `/sot-admin-api/order/makeUpDifference/createSubsidy`
      }

      const h = this.$createElement
      this.$msgbox({
        title: title,
        message: h('p', null, [
          h(
            'div',
            { style: 'font-weight: bold;font-size:18px;margin:28px 0 12px;' },
            cont
          ),
          h(
            'div',
            { style: 'color: red;font-size:16px;margin-bottom:28px;' },
            info
          )
        ]),
        showCancelButton: true,
        confirmButtonText: '确认',
        cancelButtonText: '关闭',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            done()
          } else {
            this.compensationcCount = 0
            done()
          }
        }
      }).then(action => {
        if (this.compensationcCount < 2) {
          setTimeout(() => {
            this.handleCompensation(tag, row)
          }, 368)
        } else {
          this.compensationcCount = 0
          this.ajaxCompensation(type, url, row)
        }
      })
    },
    /**
     * 请求补差接口
     * @param {String} type
     * @param {String} url
     * @param {Object} row
     * @return Void
     */

    ajaxCompensation (type, url, row) {
      const loading = this.$loading()
      this.$POST(url, {
        id: row.orderId
      })
        .then(data => {
          this.$swal.success(`${type}成功！`)
          this.getList()
        })
        .finally(e => {
          loading.close()
        })
    }
  }
}
</script>
